package com.aaa.controller;

import com.aaa.entity.Dept;
import com.aaa.entity.MyReturn;
import com.aaa.entity.PageSort;
import com.aaa.entity.Userinfo;
import com.aaa.service.DeptService;
import com.aaa.service.UserInfoService;
import com.aaa.util.MyTools;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.util.*;

@Controller
@RequestMapping("userInfo")
public class UserInfoController extends BaseController {
    MyReturn myReturn=new MyReturn();
   @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private DeptService deptService;
    /**
     * @create by: WzZz
     * @description: //查询所有用户（带分页+条件）
     * @create time: 2022/7/8 8:55
     * @param pageSort
     * @return com.aaa.entity.MyReturn
     */
    @RequestMapping("selectAllUserInfo.do")
    @ResponseBody
    public MyReturn selectAllUserInfo(PageSort pageSort) {


        System.out.println(pageSort);
        Page page = userInfoService.selectAllUserInfo(pageSort);
        MyReturn myReturn = new MyReturn();
        if (page.getResult() != null && page.getResult().size() > 0) {
            myReturn.setData(page.getResult());
            myReturn.setCount(page.getTotal());
            return super.getSuccessReturn(myReturn);
        }

        return super.getFailReturn(myReturn);
    }
    /**
     * @create by: WzZz
     * @description: //根据ID删除用户（行内工具栏）
     * @create time: 2022/7/8 8:56
     * @param userid
     * @return com.aaa.entity.MyReturn
     */
    @RequestMapping("deleteUserInfoById.do")
    @ResponseBody
    public MyReturn deleteUserInfoById(Integer userid) {
        System.out.println(userid);
        boolean deleteUserInfoById = userInfoService.deleteUserInfoById(userid);
        boolean deleteUserRoleById = userInfoService.deleteUserRoleById(userid);
        if (deleteUserInfoById&&deleteUserInfoById) {
            return super.getSuccessReturn(myReturn);
        }
        return super.getFailReturn(myReturn);
    }
    /**
     * @create by: WzZz
     * @description: //批量删除
     * @create time: 2022/7/8 8:56
     * @param userid
     * @return com.aaa.entity.MyReturn
     */
    @RequestMapping("deleteUserInfoBatch.do")
    @ResponseBody
    public MyReturn deleteUserInfoBatch(String userid) {
        System.out.println(userid);
        boolean deleteUserInfoBatch = userInfoService.deleteUserInfoBatch(userid);
        boolean deleteUserRoleBatch = userInfoService.deleteUserRoleBatch(userid);
        if (deleteUserInfoBatch&&deleteUserRoleBatch) {
            return super.getSuccessReturn(myReturn);
        }
        return super.getFailReturn(myReturn);
    }
    /**
     * @create by: WzZz
     * @description: //下拉框查询部门
     * @create time: 2022/7/8 8:56
     * @param
     * @return com.aaa.entity.MyReturn
     */
    @RequestMapping("selectDept.do")
    @ResponseBody
    public MyReturn selectDept() {
        List<Dept> deptList = deptService.selectDeptFirst();
        System.out.println(deptList);
        MyReturn myReturn = new MyReturn();
        if (deptList != null && deptList.size() > 0) {
            myReturn.setData(deptList);
            return super.getSuccessReturn(myReturn);
        }
        return super.getFailReturn(myReturn);
    }

    /**
    *@Anthor: wzzz
    @Dscription:通过头像进入页面编辑用户信息
    *@Date: 2022-07-07 10:04
    *
    **/
@RequestMapping("updateInfo.do")
@ResponseBody
public MyReturn updateInfo(Userinfo userinfo,HttpSession session){
        userinfo.setUpdate_time(new Date());
    boolean updateInfo = userInfoService.updateInfo(userinfo);
    session.setAttribute("userinfo",userinfo);
    if (updateInfo){

        return  super.getSuccessReturn(myReturn);
    }
    return super.getFailReturn(myReturn);

}
/**
*@Anthor: wzzz
@Dscription:工具栏内编辑用户信息
*@Date: 2022-07-07 10:05
*
**/
    @RequestMapping("updateUserInfo.do")
    @ResponseBody
    public MyReturn updateUserInfo(Userinfo userinfo) {
        if(userinfo.getStatus()!=1){
            userinfo.setStatus(0);
        }else{
            userinfo.setStatus(1);
        }
        userinfo.setUpdate_time(new Date());
        boolean updateUserInfo = userInfoService.updateUserInfo(userinfo);
        boolean updateUserRole = userInfoService.updateUserRole(userinfo);
        if (updateUserInfo&&updateUserRole) {
            return super.getSuccessReturn(myReturn);

        }
        return super.getFailReturn(myReturn);
    }
/**
*@Anthor: wzzz
@Dscription:重置密码
*@Date: 2022-07-07 10:06
*
**/
    @RequestMapping("resetPassword.do")
    @ResponseBody
    public MyReturn resetPassword(Userinfo userinfo) {
        userinfo.setUpdate_time(new Date());
        String password=   userinfo.getPassword();
        Map<String, String> stringStringMap = MyTools.makePasswordSalt(password);
        userinfo.setPassword(stringStringMap.get("password"));
        userinfo.setSalt(stringStringMap.get("salt"));
        boolean resetPassword = userInfoService.resetPassword(userinfo);
        MyReturn myReturn = new MyReturn();
        if (resetPassword) {
            return super.getSuccessReturn(myReturn);
        }
        return super.getFailReturn(myReturn);
    }


//    @RequestMapping("upload.do")
//    @ResponseBody
//    public MyReturn upload(MultipartFile xxx, HttpServletRequest request) {
//        //获取原始文件名
//        String filename = xxx.getOriginalFilename();
//        // 获取服务器存放上传文件的绝对路径
//        String myPath = request.getServletContext().getRealPath("myfile");
//        //初始化目标文件UUID.randomUUID()+filename;
//        // 新文件名，会保存到数据库中，如果是oss返回一个随机的http绝对连接
//        File ooo = new File(myPath, UUID.randomUUID() + filename);
//        // xxx是原始文件，将xxx复制到目标文件
//        try {
//            xxx.transferTo(ooo);
//            super.getSuccessReturn(myReturn);
//
//        } catch (IOException e) {
//            super.getFailReturn(myReturn);
//        }
//        return myReturn;
//    }


    /**
    *@Anthor: wzzz
    @Dscription:新增用户
    *@Date: 2022-07-07 10:06
    *
    **/


    @RequestMapping("insertUserInfo.do")
    @ResponseBody
    public MyReturn insertUserInfo(Userinfo userinfo) throws ClassNotFoundException {
        userinfo.setCreate_time(new Date());
     String password=   userinfo.getPassword();
        Map<String, String> stringStringMap = MyTools.makePasswordSalt(password);
        userinfo.setPassword(stringStringMap.get("password"));
        userinfo.setSalt(stringStringMap.get("salt"));
        boolean insertUserInfo = userInfoService.insertUserInfo(userinfo);
        boolean insertUserRole = userInfoService.insertUserRole(userinfo);

        if(insertUserInfo&&insertUserRole){
            return super.getSuccessReturn(myReturn);
        }
            return super.getFailReturn(myReturn);
        
    }


/**
*@Anthor: wzzz
@Dscription:上传图片
*@Date: 2022-07-07 10:06
*
**/
    @RequestMapping("upload.do")
    @ResponseBody
    public MyReturn upload(MultipartFile file) {

//获取原始文件名
        String filename = file.getOriginalFilename();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tJFEWfp97puD6zyq86B";
        String accessKeySecret = "n4iMj6VUwk0cksXqhLU7yEl00J1BuL";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "manman7531";

        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        //上传到阿里云 后的文件名
        String objectName = UUID.randomUUID() + filename;


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //原始文件

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            ossClient.putObject(putObjectRequest);
            Map<String ,Object> map=new HashMap<>();
            map.put("src","https://"+bucketName+"."+endpoint+"/"+objectName);
            myReturn.setData(map);

            return super.getUpLoadSuccessReturn(myReturn);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return super.getUpLoadFailReturn(myReturn);
    }



    /**
    *@Anthor: wzzz
    @Dscription:登录时查询用户名是否重复
    *@Date: 2022-07-07 10:06
    *
    **/
@RequestMapping("selectLoginByName.do")
@ResponseBody
    public MyReturn selectLoginByName(Userinfo userinfo){
        boolean selectLoginByName = userInfoService.selectLoginByName(userinfo);
        if (selectLoginByName){
            return  super.getFailReturn(myReturn);
        }
        return super.getSuccessReturn(myReturn);
        //名字重复则显示 失败返回-1；
    }


    }
